//
//  SNSearchViewController.m
//  ZhuoxinAgriculture
//
//  Created by stone on 16/12/16.
//  Copyright © 2016年 stone. All rights reserved.
//

#import "SNProductionPlanningViewController.h"
#import "SNProductionSearchViewNext.h"
#import "SNProductionSearchHistoryManager.h"
#import "SNSearchCollectionViewCell.h"
#import "SNProductionSearchViewController.h"
#import "SNSearchSectionHeaderView.h"
#import "SNProductionSearchSectionFooterView.h"
#import "SNCollectionViewLayoutAttributes.h"
@interface SNProductionSearchViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,SNCollectionViewLayoutDelegate>
/** searchBackgroundView */
@property (weak, nonatomic) SNProductionSearchViewNext * searchView;

/** View */
@property (weak, nonatomic) UICollectionView * collectionView;

/** titles */
@property (nonatomic,strong) NSArray<NSString *> * titles;
@end

@implementation SNProductionSearchViewController
/** titles 懒加载 */
- (NSArray<NSString *> *)titles {
    //        if (_titles == nil) {
    //              _titles = @[@"旭日农场",@"李四",@"王五",@"刘婷",@"农业合作社",@"李大白",@"周嘉嘉",@"傅天"];
    
    //            NSArray<SNSearchHistoryModel *> * array = [SNSearchHistoryModel findAll];
    _titles =  [[SNProductionSearchHistoryManager sharedManager].productionsearchHistoryModels valueForKey:@"searchText"];
    _titles = [_titles.mutableCopy reverseObjectEnumerator].allObjects;
    //        _titles = [array valueForKey:@"searchText"];
    //        }
    return _titles;
}
//===================================== stone ===========/
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
-(void)dealloc{
    //    ((SNMYNavigationController *)self.navigationController).needAnimation = @(YES);
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NeedAnimationNotification" object:@(YES) userInfo:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"种植决策人清单";
    // Do any additional setup after loading the view, typically from a nib.
    [self addSearchView];
    
    [self addCollectionView];
    
    ((SNMYNavigationController *)self.navigationController).needAnimation = @(NO);
    NSLog(@"self.navigationController = %p",self.navigationController);
}
- (UIColor *)setCollectionViewSectionBackGroundColor:(NSIndexPath *)indexPath{
    return [UIColor whiteColor];
}
- (void)addCollectionView
{
    SNCollectionViewLayout * flowLayout = [[SNCollectionViewLayout alloc] init];
    flowLayout.delegate = self;
    /** 垂直方向 间距 */
    flowLayout.sn_minimumLineSpacing = 16;
    /** 横向方向 间距 */
    flowLayout.sn_minimumInteritemSpacing = 15;
    /** 内缩 内容 */
    flowLayout.sn_sectionInset = UIEdgeInsetsMake(18.5, 25, 18.5, 25);
    
    NSInteger colNum = 4;
    
    CGFloat w =  ([UIScreen mainScreen].bounds.size.width - flowLayout.sn_sectionInset.left - flowLayout.sn_sectionInset.right - flowLayout.sn_minimumInteritemSpacing * (colNum - 1)) / colNum;
    
    /** item大小 */
    flowLayout.sn_itemSize = CGSizeMake(w,30);
    /** headerView大小 */
    flowLayout.headerReferenceSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 33);
    /** footerView大小 */
    flowLayout.footerReferenceSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 59);
    /** 滚动方向 */
    // flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    UICollectionView * collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.searchView.frame), [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - CGRectGetMaxY(self.searchView.frame)) collectionViewLayout:flowLayout];
    
    self.collectionView = collectionView;
    /** 分页处理 */
    // collectionView.pagingEnabled = YES;
    
    collectionView.backgroundColor = HexRGB(0xf5f5f5);
    collectionView.dataSource = self;
    collectionView.delegate = self;
    
    [collectionView registerNib:[UINib nibWithNibName:@"SNSearchCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"SNSearchCollectionViewCell"];
    //     :[SNSearchCollectionViewCell class] forCellWithReuseIdentifier:@"SNSearchCollectionViewCell"];
    [self.view addSubview:collectionView];
    [collectionView registerClass:[SNSearchSectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SNSearchSectionHeaderView"];
    [collectionView registerClass:[SNProductionSearchSectionFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"SNProductionSearchSectionFooterView"];
}
- (void)addSearchView
{
    SNProductionSearchViewNext * searchView = ({
        SNProductionSearchViewNext * view = [[SNProductionSearchViewNext alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 46) tapEnable:YES];
        view.textField.text = self.fullName;
        view.titleLabel.text = @"取消";
         @weakify_self
        @weakify(view)
        view.siftBlock = ^(){
            @strongify_self
            @strongify(view) //strong_tableView
            [strong_view.textField resignFirstResponder];
            [self.navigationController popViewControllerAnimated:NO];
        };
        view.reloadDataCollectionView = ^(NSString * string){
            @strongify_self
            
            NSLog(@"%@",@"11111111111111");
            
            
            [UIView animateWithDuration:0.25 animations:^{
                //[_collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
                [self.collectionView reloadData];
                
                [SNProductionPlanningViewController setNeedUPDate:YES];
                [SNProductionPlanningViewController setFullName:string];
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
            
        };
        [self.view addSubview:view];
        
        view;
    });
    self.searchView = searchView;
    
    
    //    CGSize size = searchView.textField.bounds.size;
    //    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    //
    //    CGContextRef context = UIGraphicsGetCurrentContext();
    //
    //    [searchView.textField.layer renderInContext:context];
    //
    //    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    //
    //    //	UIImageWriteToSavedPhotosAlbum(newImage, NULL, NULL, NULL);
    //    NSData * data =   UIImagePNGRepresentation(newImage);
    //
    //    [data writeToFile:@"/Users/stone/Desktop/aa.png" atomically:YES];
    //
    //    UIGraphicsEndImageContext();
}
#pragma mark - <UICollectionViewDataSource>
/** section 数量 */
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
/** item 数量 */
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    //    NSInteger count = 0;
    //    switch (section) {
    //        case 0:
    //            count = 10;
    //            break;
    //        case 1:
    //            count = 33;
    //            break;
    //        default:
    //            break;
    //    }
    return self.titles.count;
}
/** UICollectionViewCell */
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SNSearchCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SNSearchCollectionViewCell" forIndexPath:indexPath];
    //    cell.backgroundColor = [UIColor orangeColor];
    
    [cell.button setTitle:self.titles[indexPath.item] forState:UIControlStateNormal];
    
    return cell;
}
/** UICollectionReusableView */
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    if (kind == UICollectionElementKindSectionHeader) {
        //此处是headerView
        SNSearchSectionHeaderView *  headerReusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"SNSearchSectionHeaderView" forIndexPath:indexPath];
        headerReusableView.backgroundColor = [UIColor whiteColor];
        //        headerReusableView.layer.borderColor = [UIColor blackColor].CGColor;
        //        headerReusableView.layer.borderWidth = 1.0;
        return headerReusableView;
    }else if(kind == UICollectionElementKindSectionFooter){
        //此处是footerView
        SNProductionSearchSectionFooterView *  footerReusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"SNProductionSearchSectionFooterView" forIndexPath:indexPath];
        //        footerReusableView.backgroundColor = [UIColor greenColor];
        //        footerReusableView.layer.borderColor = [UIColor blackColor].CGColor;
        //        footerReusableView.layer.borderWidth = 1.0;
        @weakify_self
        footerReusableView.reloadDataCollectionView = ^(){
            @strongify_self
            //            [self.collectionView reloadData];
            [UIView animateWithDuration:0.25 animations:^{
                //[_collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
                [self.collectionView reloadData];
            }];
        };
        return footerReusableView;
    }else{
        return nil;
    }
}
#pragma mark - <UICollectionViewDelegate>
// 选中操作
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%@ | %s",self.class,__func__);
    
    SNSearchCollectionViewCell * cell = (SNSearchCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    self.searchView.textField.text = cell.button.currentTitle;
    
    NSString * string = [self.searchView.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    SNProductionSearchHistoryModel * findModel = [SNProductionSearchHistoryModel findFirstByCriteria:[NSString stringWithFormat:@"WHERE searchText = '%@'",string]];
    if (findModel) {
        // 有就摆到最前面去
        //TODO: 有就摆到最前面去
        [UIView animateWithDuration:0.25 animations:^{
            //[_collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
            [self.collectionView reloadData];
            
            [SNProductionPlanningViewController setNeedUPDate:YES];
            [SNProductionPlanningViewController setFullName:string];
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }else{
        SNProductionSearchHistoryModel * model = [SNProductionSearchHistoryModel new];
        model.searchText = string;
        if (string.length>0) {
            
            [[SNProductionSearchHistoryManager sharedManager] addObject:model];
        }
        
        [UIView animateWithDuration:0.25 animations:^{
            //[_collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
            [self.collectionView reloadData];
            
            [SNProductionPlanningViewController setNeedUPDate:YES];
            [SNProductionPlanningViewController setFullName:string];
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }
}
// 取消选中操作
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%@ | %s",self.class,__func__);
}
@end
